#include "sqliteutils.h"

DatabaseManager::DatabaseManager(QObject *parent)
    : QObject(parent)
{


}
///初始化数据库
bool DatabaseManager::initDatabase(const QString &dbPath)
{
    // 连接 SQLite
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbPath);

    if (!db.open()) {
        qWarning() << "数据库打开失败:" << db.lastError().text();
        return false;
    }
    query = QSqlQuery(db);
    qWarning() << "数据库打开成功！";
    return true;
}
///创建数据库表
bool DatabaseManager::createTables(const QString &sql)
{
    if (!query.exec(sql)) {
        qDebug() << "建表失败:" << query.lastError().text();
        return false;
    }
    return true;
}

///插入
bool DatabaseManager::insert(const OrmBase &obj)
{
    QVariantMap fieldMap = obj.toMap();
    QStringList fields = fieldMap.keys();
    QStringList placeholders;
    for (const QString &field : fields) {
        placeholders << ":" + field;
    }
    QString sql = QString("INSERT INTO %1 (%2) VALUES (%3)")
                      .arg(obj.tableName())
                      .arg(fields.join(", "))
                      .arg(placeholders.join(", "));
    QSqlQuery insertQuery(db);
    insertQuery.prepare(sql);
    for (const QString &field : fields) {
        insertQuery.bindValue(":" + field, fieldMap[field]);
    }
    if (!insertQuery.exec()) {
        qDebug() << "插入失败:" << insertQuery.lastError().text();
        return false;
    }
    return true;
}
///更新

bool DatabaseManager::update(const OrmBase &obj, const QString &whereClause)
{
    QVariantMap fieldMap = obj.toMap();
    QStringList setClauses;
    for (const QString &field : fieldMap.keys()) {
        setClauses << QString("%1 = :%1").arg(field);
    }
    QString sql = QString("UPDATE %1 SET %2 WHERE %3")
                      .arg(obj.tableName())
                      .arg(setClauses.join(", "))
                      .arg(whereClause);
    QSqlQuery updateQuery(db);
    updateQuery.prepare(sql);
    for (const QString &field : fieldMap.keys()) {
        updateQuery.bindValue(":" + field, fieldMap[field]);
    }
    if (!updateQuery.exec()) {
        qDebug() << "更新失败:" << updateQuery.lastError().text();
        return false;
    }
    return true;
}
///删除
bool DatabaseManager::remove(const OrmBase &obj, const QString &whereClause)
{
    QString sql = QString("DELETE FROM %1 WHERE %2")
                      .arg(obj.tableName())
                      .arg(whereClause);
    QSqlQuery deleteQuery(db);
    if (!deleteQuery.exec(sql)) {
        qDebug() << "删除失败:" << deleteQuery.lastError().text();
        return false;
    }
    return true;
}

//生成表字段
bool DatabaseManager::createTableFromClass(const OrmBase &obj){
    const QMetaObject *meta = obj.metaObject();  // 获取类元对象
    QString tableName = obj.tableName();
    QStringList fieldDefs;


    qDebug() << "propertyCount：" << meta->propertyCount() << ",propertyOffset:" << meta->propertyOffset();

    for (int i = meta->propertyOffset(); i < meta->propertyCount(); ++i) {
        QMetaProperty prop = meta->property(i);
        QString name = prop.name();
        QString type = prop.typeName();

        QString sqlType;
        if (type == "int" || type == "short" || type == "long" || type == "bool") {
            sqlType = "INTEGER";
        } else if (type == "double" || type == "float") {
            sqlType = "REAL";
        } else if (type == "QString" || type == "QByteArray") {
            sqlType = "TEXT";
        } else {
            sqlType = "BLOB"; // 其他类型统一用 BLOB
        }

        if (name == "id") {
            fieldDefs << QString("%1 INTEGER PRIMARY KEY AUTOINCREMENT").arg(name);
        } else {
            fieldDefs << QString("%1 %2").arg(name).arg(sqlType);
        }
    }

    QString createSQL = QString("CREATE TABLE IF NOT EXISTS %1 (\n    %2\n);")
                            .arg(tableName)
                            .arg(fieldDefs.join(",\n    "));

    QSqlQuery query;
    if (!query.exec(createSQL)) {
        qDebug() << "自动建表失败:" << query.lastError().text();
        qDebug() << "SQL语句:" << createSQL;
        return false;
    }

    qDebug() << "表创建成功:" << tableName;
    qDebug() << createSQL;
    return true;
}
